
cc.Class({
    extends: cc.Component,

    properties: {
        playerPrefabs : [cc.Prefab],
        targetNode : cc.Node
    },

    onLoad(){
    },

    resetScene(data){
        cc.log('resetScene:',data)
        this._players = {};
        this.targetNode.destroyAllChildren();
        for(var i=0; i<data.users.length; i++){
            var user = data.users[i];
            // if(user.id == global.Data.id){
                this.addUser(user);
            // }
        }
        for(var id in data.data.users){
            var d = data.data.users[id];
            if(this._players[id]){
                this._players[id].setPosition(d.point.x,d.point.y);
                this._players[id].setData({st:d.st,sa:d.sa});
            }
        }
    },

    addUser(user){
        if(this._players[user.id]){
            return this._players[user.id];
        }
        var no = cc.instantiate(this.playerPrefabs[0])
        this.targetNode.addChild(no);
        var player = no.getComponent('Player')
        this._players[user.id] = player;
        if(user.id == global.Data.id){
            this.localPlayer = player
            player.isLocal = true;
        }
        player.setOptions(user);
        player.setPosition(user.pid==0?-200:200,-200);
        
        return player
    },
    newUser(user,data){
        var p = this.addUser(user)
        if(data && data.point){
            p.setPosition(data.point.x,data.point.y);
        }
    },

    removeUser(user){
        var player = this._players[user.id]
        if(player){
            player.node.destroy();
            delete this._players[user.id]
        }
    },

    moveMessage(msg){
        // if(msg.id == global.Data.id){
            // this.moveEnd(msg)
            this._players[msg.id] && this._players[msg.id].setDirection(msg.direction);
            // if(msg.direction.x == 0 && msg.direction.y == 0){
                // cc.log('人物移动停止，校对坐标:',msg.direction);
                this.moveEnd(msg);
            // }
        // }
    },
    setShootAngle(msg){
        this._players[msg.id] && this._players[msg.id].setShootAngle(msg.sa);
    },

    moveEnd(msg){
        if(!this.isLocal && this._players[msg.id]){
            this._players[msg.id].node.x = msg.point.x;
            this._players[msg.id].node.y = msg.point.y;
            cc.log('人物移动停止，校对坐标:',msg.point);
        }
    },

    gameUpdate(dt){
        for(var id in this._players){
            this._players[id].gameUpdate(dt)
        }
    },
    frameUpdate(v){
        cc.log('frameUpdate:',v)
        for(var id in v.users){
            var user = v.users[id];
            if(this._players[id] && this._players[id] != this.localPlayer){
                this._players[id].setDirection(user.direction);
                if(user.direction.x == 0 && user.direction.y == 0){
                    this._players[id].node.x = user.point.x;
                    this._players[id].node.y = user.point.y;
                }
            }
        }
    }
});
